//detail.js
const util = require('../../utils/util.js');
const urls = require('../../utils/url.js');
const event = require('../../utils/events.js');
const win = util.getSystemHW();
Page({
  data: {
    list:[],
    scrollTop:0,
    scrollHeight:win.windowHeight,
    curActCommentIndex:-1,
    isActivate:false,
    lastId:0,
    nomore:false,
    percent:1,
    blankHeight:0,
    isAuto:false,
    comment:0,
    thumbup:0,
    muluIndex:0,
    isOver:false,
    isScrollerd:true,
    isShowCatalog:false,
  },
  roleList:[],
  contentList:[],
  muluList:[],
  touchStartTime: 0,
  touchEndTime: 0,
  atuoInterval:null,
  scrollHeight: 0,
  cover:'',
  onLoad: function (query) {
    this.curDataId = query.dataId;
    this.cover = query.dataCover;
    this.dataName = query.dataName;
    this.lastContentId = query.lastContentId;
    this.lastMuluId = query.lastMuluId;
    this.novelListIndex = query.dataIndex;
    this.novelListDirect = query.dataDirect;
    this.author={head:query.autorHead,name:query.autorName};
    this.novelInfo={desc:query.dataDesc};
    this.userObj = util.getStorageInfo('userInfo');
    this.initMuluIndex = query.dataMuluIndex?query.dataMuluIndex:0;
    var curUrl = urls.detail+"&novel_id="+this.curDataId+"&auth_key="+this.userObj.auth_key+"&mulu_id="+this.lastMuluId;
    this.getDetailData(curUrl,(res)=>{
      this.setUpData(res,true);
    });
    wx.setNavigationBarTitle({title: query.dataName});
    this.scrollHeight = this.data.scrollHeight;
  },
  onUnload: function(){
    var paramObj = {};
    var muluArr = [];
    var thisObj = this;
    paramObj.novel_id = this.curDataId;
    paramObj.auth_key = this.userObj.auth_key;
    for (var i = 0; i < this.muluList.length; i++) {
      var newMuluObj = {};
      newMuluObj.content_id = this.muluList[i]['lastContentId']&&util.isVailValue(this.muluList[i]['lastContentId'])?this.muluList[i]['lastContentId']:0;
      newMuluObj.mulu_id = this.muluList[i]['mulu_id'];
      muluArr.push(newMuluObj);
    };
    paramObj.mulu_content = JSON.stringify(muluArr);
    util.post(urls.percentage,paramObj,(res)=>{
      event.emit('DataChanged', {
        index:thisObj.novelListIndex,
        direct:thisObj.novelListDirect,
        muluId:thisObj.muluList[thisObj.initMuluIndex]["mulu_id"],
        contentId:thisObj.muluList[thisObj.initMuluIndex]["lastContentId"]
      });
    },false);
  },
  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }else{
      // 右上角转发菜单
      console.log(res.target)
    };
    return {
      title: '阅米粒--'+this.dataName,
      path: '/pages/detail/detail?dataId='+this.curDataId+'&dataName='+this.dataName+'&dataCover='+this.cover+
      '&dataDesc='+this.novelInfo.desc+'&autorHead='+this.author.head+'&autorName='+this.author.name+'&lastContentId='+
      this.lastContentId+'&lastMuluId='+this.lastMuluId+'&dataIndex='+this.novelListIndex+'&dataDirect='+this.novelListDirect,
      imageUrl:this.cover,
      success: function(res) {
        // 转发成功
        console.log(res);
      },
      fail: function(res) {
        // 转发失败
        console.log(res);
      }
    }
  },
  getDetailData: function(url,callback){
    if(util.isVailValue(url)){
      util.get(url,callback);
    }
  },
  setUpData: function(res,isFirst){
    this.roleList = res.role;
    this.contentList=res.content;
    this.muluList = isFirst?res.mulu:this.muluList;
    var totalComments = 0;
    var totalLikes = 0;
    for (var i = 0; i < this.muluList.length; i++) {
      totalComments+=(util.isVailValue(this.muluList[i]['comment_num'])?Number(this.muluList[i]['comment_num']):0);
      totalLikes+=(util.isVailValue(this.muluList[i]['like_num'])?Number(this.muluList[i]['like_num']):0);
      if(isFirst&&this.muluList[i]["mulu_id"]===this.lastMuluId){
        this.initMuluIndex = i;
      }
    };
    if(this.novelInfo&&util.isVailValue(this.novelInfo.desc)){
      this.novelInfo["comments"] = totalComments;
      this.novelInfo["likes"] = totalLikes;
    }else{
      this.novelInfo = {
        desc:res.novelInfo&&util.isVailValue(res.novelInfo.desc)?res.novelInfo.desc:this.contentList[0]["content"],
        comments:totalComments,
        likes:totalLikes
      };
    };
    if(isFirst&&util.isVailValue(this.lastContentId)&&this.lastContentId!=="0"){
      for (var k = 0; k < this.contentList.length; k++) {
        if(this.contentList[k]["id"]===this.lastContentId){
          return this.initContentList(k);
        }
      }
    }else {
      this.getNewContent(this.data.lastId,false,true);
    }
  },
  initContentList: function(lastIndex){
    var thisObjList = this.contentList;
    var newArr= [];
    var thisObj = this;
    for(var j=0;j<=lastIndex;j++){
      this.getNewContent(j,false,true,(obj)=>{
        newArr.push(obj);
        if(j===lastIndex){
          var curPercentage = Math.round((newArr.length/thisObjList.length)*10000)/100;
          thisObj.setData({
            list:newArr,
            nomore:(newArr.length===thisObjList.length)?true:false,
            bgImage:this.cover,
            lastId:j+1,
            toView:(newArr.length===thisObjList.length)?"view_controlOver":"view_"+obj.id,
            isOver:(newArr.length===thisObjList.length)?true:false,
            comment:this.muluList[thisObj.initMuluIndex]["comment_num"],
            thumbup:this.muluList[thisObj.initMuluIndex]["like_num"],
            footerHeight:3*this.scrollHeight/4,
            percent:curPercentage,
            blankHeight:thisObj.scrollHeight*0.4,
            isAuto:false,
            muluIndex:thisObj.initMuluIndex,
            isActivate:false,
          },()=>{
            util.getSeletorLoction("view_"+obj.id,thisObj,(res)=>{
              if((thisObj.scrollHeight*0.6-res.bottom)>=0){
                thisObj.setData({blankHeight:thisObj.scrollHeight-res.bottom,toView:'view_controlLayer'});
              }else{
                thisObj.setData({toView:'view_controlLayer'});
              }
            })
          });
        }
      });
    }
  },
  getNewContent: function(index,isAuto,isFirst,callback){
    var thisObjList = this.data.list;
    var curData =  this.contentList[index];
    var roleTypeObj= null;
    var hasDataObj = false;
    for (var i = 0; i < this.roleList.length; i++) {
      if(this.roleList[i].role_id===curData.role_id){
        roleTypeObj = this.roleList[i];
        var roleType =  roleTypeObj.head===''?2:roleTypeObj.lead==='1'?3:1;
        var curAvator =  roleTypeObj.head;
        var curName =  roleTypeObj.name;
        var newObj = {};
        newObj.content = curData.content;
        newObj.roleType=roleType;
        newObj.avator=curAvator;
        newObj.id=curData.id;
        newObj.name=curName;
        newObj.comment_num=curData.comment_num;
        if(callback){
          callback(newObj)
        }else{
          this.renderSingleContent(newObj,isAuto,isFirst);
        }
        return;
      }
    };
    if(curData.role_id==='0'){
      var roleType =  2;
      var curAvator =  '';
      var curName =  '';
      var newObj = {};
      newObj.content = curData.content;
      newObj.roleType=roleType;
      newObj.avator=curAvator;
      newObj.id=curData.id;
      newObj.name=curName;
      newObj.comment_num=curData.comment_num;
      if(callback){
        callback(newObj)
      }else{
        this.renderSingleContent(newObj,isAuto,isFirst);
      }
    }
  },
  renderSingleContent: function(newObj,isAuto,isFirst){
    var thisObjList = this.data.list;
    var thisObj = this;
    thisObjList.push(newObj);
    var curPercentage = Math.round((thisObjList.length/this.contentList.length)*10000)/100
    var newMuluList = this.muluList;
    newMuluList[thisObj.initMuluIndex]["percentage"] = (curPercentage<100)?(curPercentage+"%"):'已读完';
    newMuluList[thisObj.initMuluIndex]["lastContentId"] = newObj.id;
    thisObj.setData({
      list:thisObjList,
      lastId:this.data.lastId+1,
      toView:"view_"+newObj.id,
      percent:curPercentage,
      blankHeight:thisObj.scrollHeight*0.4,
      isAuto:isAuto,
      muluIndex:thisObj.initMuluIndex,
      isActivate:false,
    },()=>{
      util.getSeletorLoction("view_"+newObj.id,this,(res)=>{
        thisObj.muluList = newMuluList;
        if((thisObj.scrollHeight*0.6-res.bottom)>=0){
          thisObj.setData({blankHeight:thisObj.scrollHeight-res.bottom,toView:'view_controlLayer'});
        }else{
          thisObj.setData({toView:'view_controlLayer'});
        }
      })
    });
  },
  getMoreContent: function(e){
    var thisObj = this;
    if(thisObj.data.isActivate){
      thisObj.__closeCommentEvent(e);
    }else{
      // 控制点击事件在350ms内触发，加这层判断是为了防止长按时会触发点击事件
      if (this.touchEndTime - this.touchStartTime < 350) {
        this.getNextContent(false,false);
      }else{
        this.atuoInterval = setInterval(()=>{
          thisObj.getNextContent(true,false);
      }, 1000);
      }
    }
  },
  getNextContent: function(isAuto,isFirst){
    var curId = this.data.lastId;
    if(this.contentList.length===this.data.list.length){
      this.setData({
        nomore:true,
        percent:100,
        footerHeight:3*this.scrollHeight/4,
        bgImage:this.cover,
        toView:"view_controlOver",
        comment:this.muluList[this.data.muluIndex]["comment_num"],
        thumbup:this.muluList[this.data.muluIndex]["like_num"],
        isOver: (this.data.muluIndex===this.muluList.length-1)?true:false,
        isActivate:false,
      });
      this.stopAutoLoad();
    }else{
      this.getNewContent(curId,isAuto,isFirst);
    }
  },
  stopAutoLoad: function(){
    if(this.atuoInterval){
      clearInterval(this.atuoInterval);
      this.atuoInterval = null;
      this.setData({isAuto:false});
    }
  },
  getCommentContent: function(e){
    var thisObj = this;
    var curIndex = e.currentTarget.dataset.indexArr;
    var curDirection = e.currentTarget.dataset.aniDirection;
    this.commentContentObj = e;
    util.getSeletorLoction("view_"+e.currentTarget.dataset.scriptId,this,(res)=>{
      if(thisObj.data.curActCommentIndex===curIndex){
        thisObj.setData({isActivate:!this.data.isActivate,isScrollerd:true},()=>{
          thisObj.setData({scrollTop:(e.currentTarget.offsetTop)})
        });
      }else{
        var contentObj = thisObj.contentList[curIndex];
        var commentData={nId:contentObj.novel_id,mId:contentObj.mulu_id,cId:contentObj.id,
          dirction:curDirection,commentHeight:thisObj.scrollHeight-res.height};
        thisObj.setData({isActivate:true,curActCommentIndex:curIndex,
          commentData:commentData},()=>{
            thisObj.setData({scrollTop:(e.currentTarget.offsetTop),isScrollerd:false})
          });
      }
    })

  },
  detailUpper: function(e){

  },
  detailLower: function(e){

  },
  detailScroll: function(e){

  },
  __openCatalogEvent: function(e){
    this.setData({
      isShowCatalog:true,
      catalogData:{
        catalogList:this.muluList,
        cover:this.cover,
        name:this.dataName,
        info:this.novelInfo,
        author:this.author
      }
    })
  },
  __closeCatalogEvent: function(e){
    this.setData({
      isShowCatalog:false,
      catalogData:{}
    })
  },
  __closeCommentEvent: function(e){
    this.getCommentContent(this.commentContentObj);
  },
  __switchCatalogEvent: function(e){
    var curMuluId = e.detail.selectMuluId;
    var curMuluIndex = e.detail.selectMuluIndex;
    this.initMuluIndex = curMuluIndex;
    this.__changedCatalogContent(curMuluIndex,false);
  },
  touchStart: function (e) {
    this.touchStartTime = e.timeStamp;
  },
  touchEnd: function (e) {
    this.touchEndTime =  e.timeStamp;
  },
  __changedCatalogContent: function(newMuluIndex,isReloadMulu){
    var thisObj = this;
    var curUrl = urls.detail+"&novel_id="+this.curDataId+"&mulu_id="+this.muluList[newMuluIndex]["mulu_id"]+"&auth_key="+this.userObj.auth_key;
    this.setData({list:[],
      scrollTop:0,
      curActCommentIndex:-1,
      isActivate:false,
      lastId:0,
      nomore:false,
      percent:1,
      blankHeight:0,
      isAuto:false,
      comment:0,
      thumbup:0,
      muluIndex:newMuluIndex,
      isOver:false,
      isShowCatalog:false,
      isScrollerd:true,},()=>{
        this.getDetailData(curUrl,(res)=>{
          this.setUpData(res,isReloadMulu);
        });
      })
  },
  __readEvent: function (e){
    var isOver = this.data.isOver;
    if(isOver){
      wx.navigateBack({
        delta: 1
      })
    }else {
      var newMuluIndex = this.data.muluIndex+1;
      this.initMuluIndex = newMuluIndex;
      this.__changedCatalogContent(newMuluIndex,false);
    }
  }
})
